package reduce.fz.com.reduce.util;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ProgressBar;

import java.io.IOException;

import io.vov.vitamio.MediaPlayer;
import reduce.fz.com.reduce.activity.VideoEditDescActivity;

/**
 * Created by qingshengzheng on 16/1/10.
 */
public class VitamioOper implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnInfoListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {

    //视频宽度
    private int mVideoWidth;
    //视频高度
    private int mVideoHeight;
    //播放器
    private MediaPlayer mMediaPlayer;
    //视图
    private SurfaceView mPreview;
    private SurfaceHolder holder;
    private String path;
    private Activity mActivity;
    private static final String MEDIA = "media";
    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;
    private VideoPlayListener playlistener;
    private ProgressBar mProgressBar;
    private ProgressBar mCacheBar;
    private long currenttime = 0l;
    private long alltime = 0l;
    private View videoThum;
    private View playBtn;
    public static SurfaceView currentSurfaceView;

    /**
     * 全局变量，同时只能有一个处于播放状态
     */
    public static Boolean isPlaying;

    public void setVideoThum(View thum) {
        this.videoThum = thum;
        videoThum.setVisibility(View.VISIBLE);
    }

    public void setPlayBtn(View playBtn) {
        this.playBtn = playBtn;
        this.playBtn.setVisibility(View.VISIBLE);
    }


    /**
     * Surview销毁时是否继续播放
     */
    private Boolean isContinue = true;

    //设置缓存进度bar
    public void setBufferdBar(ProgressBar bar) {
        this.mCacheBar = bar;
        mCacheBar.setVisibility(View.GONE);
    }

    //设置进度条bar，动态调整视频播放进度
    public void setProgressBar(ProgressBar bar) {
        this.mProgressBar = bar;
    }

    //设置相关监听
    public void setVideoPlayListener(VideoPlayListener listener) {
        this.playlistener = playlistener;
    }


    /**
     * 控制播放surfaceview进度条
     */
    private Handler progressHander = new Handler() {
        public void handleMessage(Message msg) {
            if (mMediaPlayer == null) return;
            currenttime = mMediaPlayer.getCurrentPosition();
            if (mProgressBar != null) {
                int progress = Integer.parseInt((((currenttime * 100) / alltime)) + "");
                mProgressBar.setProgress(progress);
                if (progress != 100)
                    progressHander.sendEmptyMessageDelayed(0, 1000);
            }

        }
    };


    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                break;
            case MediaPlayer.MEDIA_INFO_FILE_OPEN_OK:
                long buffersize = mMediaPlayer.audioTrackInit();
                mMediaPlayer.audioInitedOk(buffersize);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                mMediaPlayer.pause();
                if (mCacheBar != null) mCacheBar.setVisibility(View.VISIBLE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                mMediaPlayer.start();
                if (mCacheBar != null) mCacheBar.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        return false;
    }


    /**
     * 播放触发相关监听，预留
     */
    public interface VideoPlayListener {
        public void beforePlay();

        public void complete();
    }


    private VitamioOper(Activity mActivity, SurfaceView surfaceView) {
        this.mActivity = mActivity;
        this.mPreview = surfaceView;
        this.mPreview.setVisibility(View.GONE);
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setFormat(PixelFormat.RGBA_8888);
    }


    public static VitamioOper instance(Activity mActivity, SurfaceView surfaceView) {
        VitamioOper vitamioOper = new VitamioOper(mActivity, surfaceView);
        return vitamioOper;
    }


    public void setUrl(String url) {
        this.path = url;
    }

    /**
     * 视频播放
     */
    public void playVideo(String url) {
        doCleanUp();
        this.path = url;
        mMediaPlayer = new MediaPlayer(mActivity);
        try {
            mMediaPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.setDisplay(holder);
        // mMediaPlayer.setBufferSize(1024*1024);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnInfoListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.prepareAsync();

        mActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    /**
     * 释放当前正在播放的surfaceview
     */
    public void setCurrentSurfaceView(SurfaceView surfaceView) {
        if (currentSurfaceView != null)
            currentSurfaceView.setVisibility(View.GONE);
        currentSurfaceView = surfaceView;
    }

    /**
     * 用户
     */
    public void play() {
        if (mMediaPlayer == null) {
            displayThum(false);
            displayPlayBtn(false);
            setCurrentSurfaceView(mPreview);
            mPreview.setVisibility(View.VISIBLE);
            playVideo(path);


        } else {
            if (mMediaPlayer.isPlaying()) {
                displayPlayBtn(true);
                mMediaPlayer.pause();
            } else {
                displayPlayBtn(false);
                mMediaPlayer.start();
            }
        }
    }


    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        if (percent != 100) {
            mMediaPlayer.pause();
            mCacheBar.setVisibility(View.VISIBLE);
        } else {
            mMediaPlayer.start();
            mCacheBar.setVisibility(View.GONE);
        }
    }

    /**
     * 重置状态
     */
    public void resetFlag() {
        mPreview.setVisibility(View.GONE);
        if (videoThum != null)
            videoThum.setVisibility(View.VISIBLE);
        if (playBtn != null)
            playBtn.setVisibility(View.VISIBLE);
        mCacheBar.setVisibility(View.GONE);
        mProgressBar.setProgress(0);
        isPlaying = false;
    }


    public void onCompletion(MediaPlayer arg0) {
        if (playlistener != null) {
            playlistener.complete();
        }
        repeat();
        //startVideoPlayback();
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        if (width == 0 || height == 0) {
            return;
        }
        mIsVideoSizeKnown = true;
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaplayer) {
        alltime = mediaplayer.getDuration();
        if (playlistener != null) {
            playlistener.beforePlay();
        }
        progressHander.sendEmptyMessage(0);
        mIsVideoReadyToBePlayed = true;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }

    }


    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        releaseMediaPlayer();
        resetFlag();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {


    }

    public void displayPlayBtn(Boolean displayBtn) {
        if (playBtn == null) return;
        if (displayBtn)
            playBtn.setVisibility(View.VISIBLE);
        else
            playBtn.setVisibility(View.GONE);
    }

    /**
     * 是否显示
     *
     * @param displayThum
     */
    public void displayThum(Boolean displayThum) {
        if (videoThum == null) return;
        if (!displayThum) {
            videoThum.setVisibility(View.GONE);
        } else {
            videoThum.setVisibility(View.VISIBLE);
        }
    }

    protected void onPause() {
        releaseMediaPlayer();
        doCleanUp();
    }

    protected void onDestroy() {
        releaseMediaPlayer();
        doCleanUp();
    }

    public void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        currenttime = 0;

        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
    }

    public void repeat() {
        mMediaPlayer.seekTo(0);
        progressHander.sendEmptyMessage(0);
    }
}
